import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Button, Table, Space, Tag, Modal, message, Form, Select, DatePicker, Input, Row, Col, Descriptions, Divider, Statistic } from 'antd';
import { SyncOutlined, SearchOutlined, QrcodeOutlined } from '@ant-design/icons';
import moment from 'moment';
import { queryMeituanGroupOrders, getMeituanGroupOrderDetail, processMeituanGroupOrder, useMeituanGroupVoucher, syncMeituanGroupOrders } from './service';
import { queryMeituanGroups } from './service';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

const MeituanGroupOrderPage = () => {
  // 状态定义
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [syncLoading, setSyncLoading] = useState(false);
  const [stores, setStores] = useState([]);
  const [groups, setGroups] = useState([]);
  const [orderDetail, setOrderDetail] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [processVisible, setProcessVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 查询表单
  const [queryForm] = Form.useForm();
  const [processForm] = Form.useForm();
  
  // 订单状态
  const orderStatusOptions = [
    { label: '全部状态', value: '' },
    { label: '已确认', value: 'CONFIRMED' },
    { label: '已完成', value: 'COMPLETED' },
    { label: '已取消', value: 'CANCELLED' },
    { label: '待确认', value: 'WAITING_CONFIRM' },
  ];

  // 处理状态
  const processStatusOptions = [
    { label: '全部', value: '' },
    { label: '待处理', value: 'pending' },
    { label: '已接单', value: 'accepted' },
    { label: '已拒绝', value: 'rejected' },
    { label: '已完成', value: 'completed' },
  ];

  // 初始加载
  useEffect(() => {
    fetchStores();
    fetchGroups();
    fetchOrders();
  }, []);

  // 获取门店列表
  const fetchStores = async () => {
    try {
      const response = await queryMeituanGroups({
        page: 1,
        page_size: 100,
        status: 1, // 只获取启用的活动
      });
      
      // 提取门店信息并去重
      const storeSet = new Set();
      const storeList = [];
      
      response.data.list.forEach(item => {
        if (!storeSet.has(item.store_id)) {
          storeSet.add(item.store_id);
          storeList.push({
            id: item.store_id,
            name: item.store_name,
          });
        }
      });
      
      setStores(storeList);
    } catch (error) {
      console.error('获取门店列表失败:', error);
    }
  };

  // 获取团购活动列表
  const fetchGroups = async () => {
    try {
      const response = await queryMeituanGroups({
        page: 1,
        page_size: 100,
        status: 1, // 只获取启用的活动
      });
      setGroups(response.data.list || []);
    } catch (error) {
      console.error('获取团购活动列表失败:', error);
    }
  };

  // 获取美团团购订单列表
  const fetchOrders = async (params = {}) => {
    setLoading(true);
    try {
      const values = await queryForm.validateFields();
      
      // 处理日期范围
      let startTime, endTime;
      if (values.dateRange && values.dateRange.length === 2) {
        startTime = values.dateRange[0].startOf('day').valueOf();
        endTime = values.dateRange[1].endOf('day').valueOf();
      }
      
      const { current, pageSize } = params;
      const response = await queryMeituanGroupOrders({
        page: current || pagination.current,
        page_size: pageSize || pagination.pageSize,
        store_id: values.storeId,
        meituan_group_id: values.groupId,
        status: values.status,
        process_status: values.processStatus,
        is_used: values.isUsed,
        start_time: startTime,
        end_time: endTime,
      });
      
      setOrders(response.data.list || []);
      setPagination({
        ...pagination,
        current: params.current || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
        total: response.data.total || 0,
      });
    } catch (error) {
      console.error('获取美团团购订单列表失败:', error);
      message.error('获取美团团购订单失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格分页变化
  const handleTableChange = (pagination, filters, sorter) => {
    fetchOrders({
      current: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  // 手动同步订单
  const handleSync = async () => {
    try {
      setSyncLoading(true);
      const values = await queryForm.validateFields();
      await syncMeituanGroupOrders({
        store_id: values.storeId,
        meituan_group_id: values.groupId,
      });
      message.success('同步订单成功');
      fetchOrders();
    } catch (error) {
      console.error('同步美团团购订单失败:', error);
      message.error('同步订单失败');
    } finally {
      setSyncLoading(false);
    }
  };

  // 重置查询表单
  const handleReset = () => {
    queryForm.resetFields();
    fetchOrders({
      current: 1,
    });
  };

  // 查看订单详情
  const showOrderDetail = async (orderId) => {
    try {
      setLoading(true);
      const response = await getMeituanGroupOrderDetail(orderId);
      setOrderDetail(response.data);
      setDetailVisible(true);
    } catch (error) {
      console.error('获取订单详情失败:', error);
      message.error('获取订单详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理订单弹窗
  const showProcessModal = (record) => {
    setCurrentOrder(record);
    setProcessVisible(true);
    processForm.resetFields();
  };

  // 确认订单
  const handleConfirmOrder = async () => {
    try {
      if (!currentOrder) return;
      
      const values = await processForm.validateFields();
      await processMeituanGroupOrder({
        id: currentOrder.id,
        status: 1,
        remark: values.remark || '',
      });
      
      message.success('订单已确认');
      setProcessVisible(false);
      fetchOrders();
    } catch (error) {
      console.error('确认订单失败:', error);
      message.error('确认订单失败');
    }
  };

  // 拒绝订单
  const handleRejectOrder = async () => {
    try {
      if (!currentOrder) return;
      
      const values = await processForm.validateFields();
      if (!values.remark) {
        message.warning('拒绝订单需要填写拒绝原因');
        return;
      }
      
      await processMeituanGroupOrder({
        id: currentOrder.id,
        status: 2,
        remark: values.remark,
      });
      
      message.success('订单已拒绝');
      setProcessVisible(false);
      fetchOrders();
    } catch (error) {
      console.error('拒绝订单失败:', error);
      message.error('拒绝订单失败');
    }
  };

  // 完成订单
  const handleCompleteOrder = async () => {
    try {
      if (!currentOrder) return;
      
      const values = await processForm.validateFields();
      await processMeituanGroupOrder({
        id: currentOrder.id,
        status: 3,
        remark: values.remark || '',
      });
      
      message.success('订单已完成');
      setProcessVisible(false);
      fetchOrders();
    } catch (error) {
      console.error('完成订单失败:', error);
      message.error('完成订单失败');
    }
  };

  // 使用团购券
  const handleUseVoucher = async (id) => {
    try {
      await useMeituanGroupVoucher(id);
      message.success('团购券使用成功');
      fetchOrders();
    } catch (error) {
      console.error('使用团购券失败:', error);
      message.error('使用团购券失败');
    }
  };

  // 确认使用团购券
  const confirmUseVoucher = (record) => {
    Modal.confirm({
      title: '确认使用团购券',
      content: `确定要使用"${record.group_title}"的团购券吗？此操作不可撤销。`,
      onOk: () => handleUseVoucher(record.id),
    });
  };

  // 渲染订单状态标签
  const renderStatusTag = (status) => {
    let color = 'default';
    let text = status;
    
    switch (status) {
      case 'WAITING_CONFIRM':
        color = 'gold';
        text = '待确认';
        break;
      case 'CONFIRMED':
        color = 'blue';
        text = '已确认';
        break;
      case 'COMPLETED':
        color = 'green';
        text = '已完成';
        break;
      case 'CANCELLED':
        color = 'red';
        text = '已取消';
        break;
      default:
        break;
    }
    
    return <Tag color={color}>{text}</Tag>;
  };

  // 渲染处理状态标签
  const renderProcessStatusTag = (status) => {
    let color = 'default';
    let text = status;
    
    switch (status) {
      case 'pending':
        color = 'orange';
        text = '待处理';
        break;
      case 'accepted':
        color = 'blue';
        text = '已接单';
        break;
      case 'rejected':
        color = 'red';
        text = '已拒绝';
        break;
      case 'completed':
        color = 'green';
        text = '已完成';
        break;
      default:
        break;
    }
    
    return <Tag color={color}>{text}</Tag>;
  };

  // 渲染使用状态标签
  const renderUsedTag = (isUsed) => {
    return isUsed === 1 ? 
      <Tag color="green">已使用</Tag> : 
      <Tag color="orange">未使用</Tag>;
  };

  // 时间戳转换为显示格式
  const formatTimestamp = (timestamp) => {
    return timestamp ? moment(timestamp).format('YYYY-MM-DD HH:mm:ss') : '-';
  };

  // 表格列定义
  const columns = [
    {
      title: '订单号',
      dataIndex: 'order_id',
      key: 'order_id',
      width: 200,
    },
    {
      title: '门店名称',
      dataIndex: 'store_name',
      key: 'store_name',
    },
    {
      title: '团购活动',
      dataIndex: 'group_title',
      key: 'group_title',
      ellipsis: true,
    },
    {
      title: '购买人信息',
      key: 'customer',
      render: (_, record) => (
        <div>
          <div>{record.user_name || '-'}</div>
          <div>{record.user_phone || '-'}</div>
        </div>
      ),
    },
    {
      title: '购买数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: renderStatusTag,
    },
    {
      title: '处理状态',
      dataIndex: 'process_status',
      key: 'process_status',
      render: renderProcessStatusTag,
    },
    {
      title: '使用状态',
      dataIndex: 'is_used',
      key: 'is_used',
      render: renderUsedTag,
    },
    {
      title: '下单时间',
      dataIndex: 'order_time',
      key: 'order_time',
      render: (timestamp) => formatTimestamp(timestamp),
    },
    {
      title: '总金额',
      dataIndex: 'total_price',
      key: 'total_price',
      render: (text) => `¥${(text / 100).toFixed(2)}`,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showOrderDetail(record.id)}>查看详情</a>
          {record.process_status === 'pending' && record.status === 'WAITING_CONFIRM' && (
            <a onClick={() => showProcessModal(record)}>处理订单</a>
          )}
          {record.is_used === 0 && (record.process_status === 'accepted' || record.process_status === 'completed') && (
            <a onClick={() => confirmUseVoucher(record)}>使用券</a>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card style={{ marginBottom: 16 }}>
        <Form 
          form={queryForm}
          layout="inline"
          initialValues={{
            status: '',
            processStatus: '',
            isUsed: '',
            dateRange: [moment().subtract(7, 'days'), moment()],
          }}
          onFinish={() => fetchOrders({ current: 1 })}
        >
          <Row gutter={[16, 16]} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item
                name="storeId"
                label="门店"
                style={{ width: '100%' }}
              >
                <Select placeholder="选择门店">
                  <Option value="">全部门店</Option>
                  {stores.map(store => (
                    <Option key={store.id} value={store.id}>{store.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="groupId"
                label="团购活动"
                style={{ width: '100%' }}
              >
                <Select placeholder="选择团购活动">
                  <Option value="">全部活动</Option>
                  {groups.map(group => (
                    <Option key={group.id} value={group.id}>{group.title}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="status"
                label="订单状态"
                style={{ width: '100%' }}
              >
                <Select>
                  {orderStatusOptions.map(option => (
                    <Option key={option.value} value={option.value}>{option.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="processStatus"
                label="处理状态"
                style={{ width: '100%' }}
              >
                <Select>
                  {processStatusOptions.map(option => (
                    <Option key={option.value} value={option.value}>{option.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[16, 16]} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item
                name="isUsed"
                label="使用状态"
                style={{ width: '100%' }}
              >
                <Select>
                  <Option value="">全部</Option>
                  <Option value="1">已使用</Option>
                  <Option value="0">未使用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="dateRange"
                label="下单时间"
                style={{ width: '100%' }}
              >
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row style={{ marginTop: 16 }}>
            <Col>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  查询
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
                <Button 
                  type="primary" 
                  ghost 
                  onClick={handleSync} 
                  loading={syncLoading}
                  icon={<SyncOutlined />}
                >
                  同步订单
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>
      
      <Card>
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
        />
      </Card>

      {/* 订单详情弹窗 */}
      <Modal
        title="团购订单详情"
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
      >
        {orderDetail && (
          <>
            <Descriptions title="基本信息" column={2} bordered>
              <Descriptions.Item label="订单号">{orderDetail.order_id}</Descriptions.Item>
              <Descriptions.Item label="门店名称">{orderDetail.store_name}</Descriptions.Item>
              <Descriptions.Item label="团购活动">{orderDetail.group_title}</Descriptions.Item>
              <Descriptions.Item label="下单时间">{formatTimestamp(orderDetail.order_time)}</Descriptions.Item>
              <Descriptions.Item label="订单状态">{renderStatusTag(orderDetail.status)}</Descriptions.Item>
              <Descriptions.Item label="处理状态">{renderProcessStatusTag(orderDetail.process_status)}</Descriptions.Item>
              <Descriptions.Item label="使用状态">{renderUsedTag(orderDetail.is_used)}</Descriptions.Item>
              {orderDetail.use_time && (
                <Descriptions.Item label="使用时间">{formatTimestamp(orderDetail.use_time)}</Descriptions.Item>
              )}
              <Descriptions.Item label="购买人">{orderDetail.user_name}</Descriptions.Item>
              <Descriptions.Item label="联系电话">{orderDetail.user_phone}</Descriptions.Item>
              <Descriptions.Item label="购买数量">{orderDetail.quantity}</Descriptions.Item>
              <Descriptions.Item label="订单金额">¥{(orderDetail.total_price / 100).toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="团购券码" span={2}>
                {orderDetail.voucher_code || '-'}
                {orderDetail.voucher_code && orderDetail.is_used === 0 && (
                  <Button 
                    type="primary" 
                    size="small" 
                    icon={<QrcodeOutlined />} 
                    style={{ marginLeft: 8 }}
                    onClick={() => confirmUseVoucher(orderDetail)}
                  >
                    使用券
                  </Button>
                )}
              </Descriptions.Item>
              {orderDetail.voucher_valid_time && (
                <Descriptions.Item label="券有效期" span={2}>
                  {formatTimestamp(orderDetail.voucher_valid_time)}
                </Descriptions.Item>
              )}
              <Descriptions.Item label="备注" span={2}>{orderDetail.remark || '-'}</Descriptions.Item>
              <Descriptions.Item label="美团备注" span={2}>{orderDetail.meituan_remark || '-'}</Descriptions.Item>
            </Descriptions>
          </>
        )}
      </Modal>

      {/* 处理订单弹窗 */}
      <Modal
        title="处理团购订单"
        visible={processVisible}
        onCancel={() => setProcessVisible(false)}
        footer={null}
      >
        {currentOrder && (
          <>
            <Descriptions column={1} bordered style={{ marginBottom: 16 }}>
              <Descriptions.Item label="订单号">{currentOrder.order_id}</Descriptions.Item>
              <Descriptions.Item label="门店名称">{currentOrder.store_name}</Descriptions.Item>
              <Descriptions.Item label="团购活动">{currentOrder.group_title}</Descriptions.Item>
              <Descriptions.Item label="下单时间">{formatTimestamp(currentOrder.order_time)}</Descriptions.Item>
              <Descriptions.Item label="订单金额">¥{(currentOrder.total_price / 100).toFixed(2)}</Descriptions.Item>
            </Descriptions>

            <Form form={processForm} layout="vertical">
              <Form.Item
                name="remark"
                label="备注/拒绝原因"
              >
                <TextArea rows={4} placeholder="请输入备注或拒绝原因" />
              </Form.Item>

              <div style={{ textAlign: 'center' }}>
                <Space size="middle">
                  <Button type="primary" onClick={handleConfirmOrder}>
                    确认接单
                  </Button>
                  <Button danger onClick={handleRejectOrder}>
                    拒绝订单
                  </Button>
                  <Button onClick={() => setProcessVisible(false)}>
                    取消
                  </Button>
                </Space>
              </div>
            </Form>
          </>
        )}
      </Modal>
    </PageContainer>
  );
};

export default MeituanGroupOrderPage; 